<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">

  <!-- CSRF -->
  <meta name="_csrf" th:content="${_csrf.token}"/>
  <!-- default header name is X-CSRF-TOKEN -->
  <meta name="_csrf_header" th:content="${_csrf.headerName}"/>

  <title>Spring Boot Starter Front Application</title>
</head>
<body>
<h2>User Information</h2>
<div id="user-logged-in" style="display: none">
  <p id="user-info"></p>
  <p><a href="/user">My Home</a></p>
  <p><a href="/user/chat">My Chat</a></p>
  <p><a href="/article/create">Create Article</a></p>
  <p><a href="/account/updatePassword">Update Password</a></p>
  <p><a href="" id="to-logout">Logout</a></p>
</div>
<div id="user-login">
  <p><a href="/account/login">Login</a></p>
  <p><a href="/account/register">Sign Up</a></p>
</div>
<h2>Article</h2>
<p id="article-info"></p>
<table style="width: 100%;">
  <thead>
  <tr>
    <td>Id</td>
    <td>Title</td>
    <td>Read Count</td>
    <td>Support Count</td>
    <td>Article Summary</td>
    <td>User Id</td>
    <td>Create Time</td>
    <td>Update Time</td>
    <td>Operations</td>
  </tr>
  </thead>
  <tbody id="article-tbody"></tbody>
</table>
</body>
<script>
  const csrf = document.getElementsByName('_csrf')[0].getAttribute('content');
  const csrfHeader = document.getElementsByName('_csrf_header')[0].getAttribute('content');

  fetch('/api/article/list').then(res => res.json()).then(res => {
    document.getElementById('article-tbody').innerHTML = res.data.list.map(item => `
      <tr>
        <td>${item.id}</td>
        <td>${item.title}</td>
        <td>${item.readCount}</td>
        <td>${item.supportCount}</td>
        <td>${item.intro}</td>
        <td>${item.frontUserId}</td>
        <td>${item.createTime}</td>
        <td>${item.updateTime}</td>
        <td><a href="/article/record/${item.id}">Detail</a></td>
      </tr>
    `).join('');
    document.getElementById('article-info').innerText = `pageNum: ${
      res.data.pageNum
      }, pageSize: ${res.data.pageSize}, pages: ${res.data.pages}, total: ${
      res.data.total
      }`;
  });
  document.getElementById('to-logout').addEventListener('click', () => {
    fetch('/api/account/logout', {
      method: 'post',
      headers: {
        [csrfHeader]: csrf,
      },
    }).then(res => res.json()).then(res => {
      if (res.message) {
        alert(res.message);

        if (res.code === 0) location.href = '/';
      }
    });
  }, !1);
  fetch('/api/account/currentUser').then(res => res.json()).then(res => {
    const userInfo = document.getElementById('user-info');
    const userLoggedIn = document.getElementById('user-logged-in');
    const userLogin = document.getElementById('user-login');
    if (res.data) {
      userLoggedIn.style.display = 'block';
      userLogin.style.display = 'none';
      userInfo.innerHTML = `Id: ${res.data.id}, Username: ${res.data.username}, Email: ${res.data.email}`;
    }
  });
</script>
</html>
